
local application = class("application")
local log = z9.log

function application:ctor()
    self._loop = z9.event_loop.new()  --一个App只有一个loop，不管启动几个server
end 

function application:newHttpServer( strIp, intPort)
    local httpserver = z9.HTTP.easyServer(
        function(request, response)
            local body = request:getBody()    

            local _sess = z9.sessionHttp:create(request, response)
            local _rpc = z9.rpc:create(_sess)
            local strResp = _rpc:processJson(body)
            if strResp then
                z9.HTTP.say(response, strResp)
            end
        end
    )
    httpserver:listen(self._loop, strIp, intPort)
    return httpserver
end 

function application:newTcpServer(strIp, intPort)
--TODO 所有session集合的处理
    local tcpserver = z9.socket.stream.ip4.listen(self._loop, strIp, intPort,
        function(fd, err, strIp, intPort)  
            local conn = z9.socket.stream.new(fd, z9.const.tcp_buff_size, z9.packet.decoder(65535))
            if conn then
                z9.log.Info("--- a new conn ---: " ..strIp..":"..intPort )
                local _sess = z9.sessionTcp:create(conn)
                
                local _rpc = z9.rpc:create(_sess)
                local ret = conn:start(self._loop, function(data)
                    if data then
                        local rpacket = packet.reader(data)
                        local rawMessage = rpacket:readStr()
                        _rpc:processSproto(rawMessage)
                    else
                        print("no data-- client close")
                        _sess:close()
                    end 
                end)
                if ret then
                    --TODO: have err
                    z9.log.Info("Have err")
                end 
            end 
        end
    )
    return tcpserver
end 

function application:newHttpClient(strIp, intPort)
    return z9.httpclient:create(self._loop, strIp, intPort)
end 

function application:newRedisConn( strIp, intPort)
    if self._db then 
        return self._db
    end 
    self._db = z9.redisdb:create(self._loop, strIp, intPort)
    return self._db
end 

function application:newTimer()
    
end 

function application:getLoop()
    return self._loop
end 

function application:add()
    
end 

function application:start()
    self._loop:watchSignal(z9.signal.SIGINT, function()
        z9.log.Info("-----SIGINT------")
        self._loop:stop()
        self._loop = nil 
    end)

    self._loop:run()
end 

return application
